const bcrypt = require('bcrypt');
const { User, validateSchema } = require('../../model/user');
module.exports = async(req, res, next) => {
    try {
        await validateSchema(req.body);
    } catch (er) {
        // return res.redirect(`/admin/user-edit?err=${er.message}`);
        return next(JSON.stringify({ path: '/admin/user-edit', message: er.message }));
    };
    let user = await User.findOne({ email: req.body.email });
    if (user) {
        // return res.redirect('/admin/user-edit?err=邮箱已被注册');
        //next()第一个参数是字符串
        return next(JSON.stringify({ path: '/admin/user-edit', message: '邮箱已被注册' }));
    }
    let salt = await bcrypt.genSalt(10);
    req.body.password = await bcrypt.hash(req.body.password, salt);
    await User.create(req.body);
    res.redirect('/admin/user');

}